import { defineEventHandler, getQuery } from 'h3';

export function createTransactionsApi(app) {
  return defineEventHandler(async (event) => {
    console.log(`📊 Transactions API 被调用: ${event.node.req.method} ${event.node.req.url}`);
    
    if (event.node.req.method === 'GET') {
      console.log('✅ 确认是GET请求，开始处理...');
      try {
        const query = getQuery(event);
        console.log('📖 查询参数:', query);
        
        const limit = parseInt(query.limit) || 100;
        const offset = parseInt(query.offset) || 0;
        console.log(`📊 查询参数: limit=${limit}, offset=${offset}`);
        
        console.log('🗄️ 正在查询数据库...');
        console.log('🔍 数据库状态:', !!app.database, !!app.database?.db);
        
        if (!app.database) {
          throw new Error('数据库未初始化');
        }
        
        const transactions = app.database.getTransactions(limit, offset);
        const total = app.database.getStats().totalTransactions;
        
        console.log(`📊 查询结果: 返回${transactions.length}条记录，总计${total}条`);
        
        return { data: transactions, total };
      } catch (error) {
        console.error('❌ Transactions API 错误:', error);
        throw error;
      }
    } else if (event.node.req.method === 'DELETE') {
      console.log('🗑️ 确认是DELETE请求，开始清空所有记录...');
      try {
        if (!app.database) {
          throw new Error('数据库未初始化');
        }
        
        const result = app.database.clearAllRecords();
        console.log('✅ 数据库记录清空成功');
        
        // 通过WebSocket广播清空事件
        if (app.webSocketServer) {
          app.webSocketServer.broadcast({
            type: 'records_cleared',
            data: { message: '所有记录已清空' },
            timestamp: Date.now()
          });
          console.log('📡 已广播记录清空事件');
        }
        
        return result;
      } catch (error) {
        console.error('❌ 清空记录失败:', error);
        event.node.res.statusCode = 500;
        return { 
          success: false, 
          error: error.message || '清空记录失败' 
        };
      }
    } else {
      console.log(`❌ 不支持的请求方法: ${event.node.req.method}`);
      event.node.res.statusCode = 405;
      return { error: 'Method Not Allowed' };
    }
  });
}

export function createTransactionDetailApi(app) {
  return defineEventHandler(async (event) => {
    if (event.node.req.method === 'GET') {
      const id = event.context.params.id;
      const transaction = app.database.getTransaction(id);
      
      if (!transaction) {
        event.node.res.statusCode = 404;
        return { error: 'Transaction not found' };
      }
      
      return { data: transaction };
    }
  });
} 